package com.alibaba.citrus.cr.sales.plan.facade.service.statistics;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.lock.RedisLock;
import com.alibaba.citrus.cr.common.log.CommonErrorCode;
import com.alibaba.citrus.cr.sales.plan.api.statistics.SalesPlanStatService;
import com.alibaba.citrus.cr.sales.plan.contants.SalesPlanConstants;
import com.alibaba.citrus.cr.sales.plan.contants.SalesPlanLockKey;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanLineDealService;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.salesplandetailstat.dto.PlanStatServiceWithUpdatePrincipalRequest;
import com.epoch.app.bcorder.salesplandetailstat.service.SalesPlanDetailStatService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yifei
 * @since 2022/12/19
 */
@Component
public class SalesPlanDetailStatServiceImpl implements SalesPlanDetailStatService {

    private static final Log log = Log.getLogger(SalesPlanDetailStatServiceImpl.class);

    @Resource
    private SalesPlanStatService salesPlanStatService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanLineDealService salesPlanLineDealService;

    @FacadeInvoker
    @Override
    public Result<Boolean> planStatServiceWithUpdatePrincipal(PlanStatServiceWithUpdatePrincipalRequest request) {
        if (Boolean.TRUE.equals(request.getUpdateManagerFlag())) {
            String planId = "#".equals(request.getPlanId().substring(0, 1)) ? request.getPlanId().substring(1) : request.getPlanId();
            try (RedisLock lock = new RedisLock(BcOrderConstants.REDIS_CACHE_CODE(), SalesPlanLockKey.getPlanStatWithUpdatePrincipalLockKey(planId))) {
                boolean locked = lock.lock();
                if (!locked) {
                    log.error("SalesPlanDetailStatServiceImpl planStatServiceWithUpdatePrincipal.fail planId=" + planId);
                    return Result.fail("OTS-02-006-00-16-005", "该计划正在汇总，请稍后重试");
                }
                // 获取月度计划
                SalesPlanSDO salesPlanSDO = getSalesPlanSDO(planId);
                if (!SalesPlanConstants.SALES_PLAN_STATUS_UPDATE_MANAGER.contains(salesPlanSDO.getStatus())) {
                    return Result.fail("OTS-02-006-00-16-021", "当前月度计划状态不允许更新计划明细销售负责人");
                }
                Result<Boolean> result = salesPlanLineDealService.updateManagerForSalesPlanDetail(salesPlanSDO);
                if (!result.isSuccess()) {
                    return result;
                }
            } catch (Exception e) {
                log.error("SalesPlanDetailStatServiceImpl planStatServiceWithUpdatePrincipal_fail: ", e);
                return Result.fail(CommonErrorCode.SYSTEM_ERROR, "系统开小差了");
            }
        }
        return salesPlanStatService.planCollect(request.getPlanId());
    }

    /**
     * 获取月度计划
     * @param planId 计划id
     * @return 结果
     */
    private SalesPlanSDO getSalesPlanSDO(String planId) {
        QuerySalesPlanRequest salesPlanRequest = new QuerySalesPlanRequest();
        salesPlanRequest.setId(planId);
        SalesPlanSDO salesPlanSDO = salesPlanRepository.load(salesPlanRequest);
        if (salesPlanSDO == null) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        if (SalesPlanStatusEnum.CANCEL.getCode().equals(salesPlanSDO.getStatus())) {
            //计划已经取消
            throw new FacadeException("OTS-02-002-00-16-003");
        }
        return salesPlanSDO;
    }
}
